package com.github.catvod.spider;

import android.content.Context;
import android.text.TextUtils;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.SSLSocketFactoryCompat;
import com.github.catvod.utils.Util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zhixc
 * 哔哩兔
 */
public class F55 extends Spider {

    private static String siteUrl = "";


    /**
     * 爬虫代码初始化
     *
     * @param context 上下文对象
     * @param extend  配置文件的 ext 参数
     */
    @Override
    public void init(Context context, String extend) {
        super.init(context, extend);
        // 域名经常性发生变化，通过外部配置文件传入，可以方便修改
        if (extend.endsWith("/")) {
            extend = extend.substring(0, extend.lastIndexOf("/"));
        }
        siteUrl = extend + "/";
    }

    /**
     * 首页内容
     */
    @Override
    public String homeContent(boolean filter) {
        try {

            JSONObject movieType = new JSONObject()
                    .put("type_id", "1")
                    .put("type_name", "电影");

            JSONObject teleplayType = new JSONObject()
                    .put("type_id", "2")
                    .put("type_name", "连续剧");

            JSONObject varietyType = new JSONObject()
                    .put("type_id", "3")
                    .put("type_name", "综艺");

            JSONObject anime = new JSONObject()
                    .put("type_id", "4")
                    .put("type_name", "动漫");

//            JSONObject sex = new JSONObject()
//                    .put("type_id", "5")
//                    .put("type_name", "午夜");

            JSONArray classes = new JSONArray()
                    .put(movieType)
                    .put(teleplayType)
                    .put(varietyType)
                    .put(anime);
//                    .put(sex);

            // filter 二级筛选 end
            JSONObject result = new JSONObject()
                    .put("class", classes);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 分类页面
     *
     * @param tid    影片分类id值
     * @param pg     第几页
     * @param extend 筛选
     * @return 返回 json 字符串
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        try {
//            HashMap<String, String> ext = new HashMap<>();
//            if (extend != null && extend.size() > 0) {
//                ext.putAll(extend);
//            }
//            String area = ext.get("area") == null ? "" : ext.get("area");
//            String year = ext.get("year") == null ? "" : ext.get("year");
//            String by = ext.get("by") == null ? "" : ext.get("by");
//            String classType = ext.get("class") == null ? "" : ext.get("class");
//            String lang = ext.get("lang") == null ? "" : ext.get("lang");
            //https://www.olevod.com/index.php/vod/show/id/2/page/1.html
            String cateUrl = siteUrl + String.format("vodshow/%s--------%s---.html", tid, pg);
            // 分类页链接拼接后应该是类似这样的：
            // cateUrl = "https://www.bilituys.com/bilishow/1-大陆-time-喜剧-国语----2---2020.html";
            String content = getWebContent(cateUrl);
            Elements lis = Jsoup.parse(content).select("a[class=module-poster-item module-item]");

            JSONArray videos = new JSONArray();
            for (Element li : lis) {
                // Element item = li.select("[class=stui-vodlist__thumb lazyload]").get(0);
                String vid = li.attr("href");
                String name = li.attr("title");
                String pic = li.select("img[data-original]").attr("data-original");
                String marks = li.select("div[class=module-item-note]").text();
//                if (tid.equals("1")) {
//                    marks = li.getElementsByClass("text_right").text();
//                } else {
//                    marks = li.getElementsByClass("pic_text").text();
//                }

                //String remark = item.select(".pic-text").select("b").text();
//                JSONObject detailObj = new JSONObject().put("detailUrl", vid).put("pic", pic);
//
                JSONObject vod = new JSONObject()
                        .put("vod_id", vid)
                        .put("vod_name", name)
                        .put("vod_pic", pic)
                        .put("vod_remarks", marks);
                videos.put(vod);
            }
            JSONObject result = new JSONObject()
                    .put("page", Integer.parseInt(pg))
                    .put("pagecount", Integer.MAX_VALUE)
                    .put("limit", lis.size())
                    .put("total", Integer.MAX_VALUE)
                    .put("list", videos);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getWebContent(String targetUrl) throws IOException {
        String ip = Util.getRandomIp();
        String ua = Util.getRandomUserAgent();
        Request request = new Request.Builder()
                .url(targetUrl)
                .get()
                .addHeader("User-Agent", ua)
                .addHeader("Host", "555uu.online")
                .addHeader("x-forwarded-for", ip)
                .build();


        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                //.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.9.149", 10811)))
                .sslSocketFactory(new SSLSocketFactoryCompat(), SSLSocketFactoryCompat.trustAllCert)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.body() == null) return "";
        String content = response.body().string();
        response.close();
        return content;
    }

    /**
     * 详情页
     */
    @Override
    public String detailContent(List<String> ids) {
        try {
//            JSONObject detailObj = new JSONObject(ids.get(0));
//            String detailUrl = detailObj.optString("detailUrl");
//            String pic = detailObj.optString("pic");

//            String durl = ids.get(0);
            System.out.println(("地址：" + ids.get(0)));
            String content = getWebContent(siteUrl + ids.get(0));

            Document detailPage = Jsoup.parse(content);
            //Elements sourceList = detailPage.select("[class=stui-content__playlist sort-list maxheight clearfix]");
            //Elements sourceHeader = detailPage.select("h3[class=title]");


            // 影片标题
            String title = detailPage.select("div[class=module-info-heading] > h1").text();
            // 图片
            String pic = detailPage.select("img[class=ls-is-cached lazy lazyload]")
                    .attr("src");

            String typeName = "";
            String year = "";
            String area = "";
            String remark = "";
            //演员
            String actor = "mddd";
            //导演
            String director = "md";
            //简介
            String brief = "md123";

            String vodPlayFrom = "f55";


            Elements vodFroms = detailPage.select("div[data-dropdown-value] > span");
            Elements playUrl = detailPage.select("div[class=module-list sort-list tab-list his-tab-list]");
            List<String> vodFList = new ArrayList<>();
            System.out.println("下标溢出？：11111111111111111111111");
            StringBuilder vodPlayUrl = new StringBuilder();
            for (int i = 0; i < vodFroms.size(); i++) {
                vodFList.add(vodFroms.get(i).text());
                Elements aurls = playUrl.get(i).select("a[class=module-play-list-link]");
                for (int j = 0; j < aurls.size(); j++) {
                    String text = aurls.get(j).text();
                    String href = siteUrl + aurls.get(j).attr("href");
                    vodPlayUrl.append(text).append("$").append(href);
                    boolean notLastEpisode = j < aurls.size() - 1;
                    vodPlayUrl.append(notLastEpisode ? "#" : "$$$");
                }


            }
            String vod_play_from = TextUtils.join("$$$", vodFList);
            System.out.println("下标溢出？：2222222222222222222222222222");
            // 影片名称、图片等赋值
            JSONObject vod = new JSONObject()
                    .put("vod_id", ids.get(0))
                    .put("vod_name", title)
                    .put("vod_pic", pic)
                    .put("type_name", typeName) // 影片类型
                    .put("vod_year", year) // 影片年份
                    .put("vod_area", area) // 影片地区
                    .put("vod_remarks", remark)
                    .put("vod_actor", actor)
                    .put("vod_director", director)
                    .put("vod_content", brief)
                    .put("vod_play_from", vod_play_from)
                    .put("vod_play_url", vodPlayUrl.toString());

            JSONArray jsonArray = new JSONArray()
                    .put(vod);
            JSONObject result = new JSONObject()
                    .put("list", jsonArray);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 搜索
     *
     * @param key 关键字/词
     */
    @Override
    public String searchContent(String key, boolean quick) {
        try {
            String searchUrl = siteUrl + "vodsearch/-------------.html?wd=" + key;
            String searchResult = getWebContent(searchUrl);
            Elements lis = Jsoup.parse(searchResult).select("a[class=module-card-item-poster]");
            JSONArray videos = new JSONArray();

            for (Element li : lis) {
                String vid = li.attr("href");
                String name = li.select("img[data-original]").attr("alt");
                String pic = li.select("img[data-original]").attr("data-original");
                String remark = li.select("[class=module-item-note]").text();
                JSONObject vod = new JSONObject()
                        .put("vod_id", vid)
                        .put("vod_name", name)
                        .put("vod_pic", pic)
                        .put("vod_remarks", remark);
                videos.put(vod);
            }
            JSONObject result = new JSONObject()
                    .put("list", videos);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) {
        try {

            //   String content = getWebContent(id);
//            content = content.substring(content.indexOf("\"link_pre\""));
//            content = content.substring(content.indexOf("\"url\":"));
//            content = content.substring(content.indexOf("\"url\":") + 7, content.indexOf("\",")).replace("\\", "");

            HashMap<String, String> header = new HashMap<>();
            //   header.put("user-agent", userAgent);
            JSONObject result = new JSONObject()
                    .put("parse", 1)
                    .put("header", getHeaders(""))
                    .put("playUrl", "")
                    .put("url", id);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    private HashMap<String, String> getHeaders(String url) {
        String ip = Util.getRandomIp();
        String ua = Util.getRandomUserAgent();
        HashMap<String, String> headers = new HashMap<>();
        //headers.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
        headers.put("User-Agent", ua);
        headers.put("Host", "555uu.online");
        headers.put("x-forwarded-for", ip);
        return headers;
    }
}
